'''
Created on Aug 2, 2012

@author: loic
'''

import os, sys, csv, re, sqlite3
from subprocess import Popen,PIPE
from optparse import OptionParser

input_dirs = ['.']
fields = ['dir', 'concat', 'size', 'new', 'new_old', 'old', 'split', 'select']

#dir = os.getcwd()
filename = '/home/loic/mp3list2.csv'

def readdir_sq(dir, spec=None):
    conn = sqlite3.connect('/home/loic/mp3.sqlite')
    c = conn.cursor()
    if dir == '.': dir = os.getcwd()
    one = os.listdir(dir)
    try:
        for o in one:
    #        print o
            dir_o = dir+'/'+o
            if not os.path.isdir(dir_o):
                continue
    #        print o
            two = os.listdir(dir_o)
            for t in two:
                dir_t = dir_o+'/'+t
                if not os.path.isdir(dir_t):
                    continue
#                    print '-->'+f
                s1 = Popen(['du', '-s', dir_t], stdout=PIPE).stdout.read()
                s2 = s1.split()
                s3 = int(s2[0])
                concat = u'%s_%s' % (o, t)
                c.execute('select concat from folders where concat=?', (concat,))
                if len(c.fetchall()) == 0:
                    col = {}
                    col['new'] = col['new_old'] = col['old'] = col['split'] = col['not_orig'] = col['best'] = False
                    if spec in ('new', 'new_old', 'old', 'split', 'not_orig'):
                        col[spec] = True
#                        c.execute('insert into ? values (?)', (spec, concat))
                    c.execute('insert into folders values (?, ?, ?, ?, ?, ?, ?, ?, ?)', (concat, unicode(dir_t), s3, col['new'], col['new_old'], col['not_orig'], col['old'], col['split'], col['best']))
                    conn.commit()
                    print '%s\t%s_%s added' % (dir_t, o, t)
                else:
                    print '%s\t%s_%s already exists' % (dir_t, o, t)
    except IndentationError:
        pass
    c.close()

def readdir():
    global dir    

    writer = csv.writer(open(filename, 'ab'), dialect=csv.excel)
    writer.writerow(fields)
    for dir in input_dirs:
        if dir == '.': dir = os.getcwd()
        one = os.listdir(dir)
        try:
            for o in one:
        #        print o
                dir_o = dir+'/'+o
                if not os.path.isdir(dir_o):
                    continue
        #        print o
                two = os.listdir(dir_o)
                for t in two:
                    dir_t = dir_o+'/'+t
#                    print '-->'+f
                    s1 = Popen(['du', '-s', dir_t], stdout=PIPE).stdout.read()
                    s2 = s1.split()
                    s3 = s2[0]
        ##            print s
        #            print '-->'+s1
        #            print s2
        #            print '---->'+s3
                    writer.writerow([dir_t, '%s_%s' % (o, t), s2[0],'','','','',''])
                    print '%s\t%s_%s' % (dir_t, o, t)
        except:
            pass
        
def read_key(dir = '/media/PUBLIC'):
    dir_re = re.compile('^\d\d\d$')
    albums = []
    one = os.listdir(dir)
    for o in one:
        dir_o = dir+'/'+o
        if not dir_re.match(o) or not os.path.isdir(dir_o):
            continue
        two = os.listdir(dir_o)
        for t in two:
            dir_t = dir_o+'/'+t
            if not dir_re.match(o) or not os.path.isdir(dir_o):
                continue
            st = t.split('_')
            print st

def read_key_sq(dir = '/media/PUBLIC'):
    conn = sqlite3.connect('/home/loic/mp3.sqlite')
    c = conn.cursor()
    dir_re = re.compile('^\d\d\d$')
    albums = []
    one = os.listdir(dir)
    for o in one:
        dir_o = dir+'/'+o
        if not dir_re.match(o) or not os.path.isdir(dir_o):
            continue
        two = os.listdir(dir_o)
        for t in two:
            dir_t = dir_o+'/'+t
            if not dir_re.match(o) or not os.path.isdir(dir_o):
                continue
            st = t.split('_')
            print st
 
def add_album(args):
    path = args[0]
    if not os.path.isdir(path):
        print "%s is not a directory"
        sys.exit()
    (head,album) = os.path.split(path)
    (head,artist) = os.path.split(head)
    
    pass
        
if __name__ == '__main__':
    parser = OptionParser()
#    parser.add_option("-a", "--artist", dest="artist",
#                  help="fix artist", action="store_true", default=False)
    (options, args) = parser.parse_args()
    if (args[0] == 'readdir'):
        readdir_sq()
    elif (args[0] == 'readkey'):
        read_key()
    elif (args[0] == 'addalbum'):
        add_album(args[1-])
#    readdir_sq('/home/loic/mp3')
#    readdir_sq('/net/srv/data/mp3/Divers', 'not_orig')
#    readdir_sq('/net/srv/data/mp3/Originaux')
